package com.smart.seven.aop.advice.introductioninterceptor;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

/**
 * 性能监视实现类
 *
 * @author junrui.wang
 * @create 2018/7/24
 */
public class ControllablePerformanceMonitor
        extends DelegatingIntroductionInterceptor
        implements Monitorable {

    //通过ThreadLocal保存与调用线程相关的状态（ThreadLocal是将非线程安全类改造成线程安全类的“法宝”）
    private static ThreadLocal<Boolean> MonitorStatus =
            new ThreadLocal<Boolean>();

    //拦截方法
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object obj = null;
        //根据状态判断是否开启性能监控
        if(MonitorStatus.get() != null && MonitorStatus.get()){
            PerformanceMonitor.begin(mi.getClass().getName() + "." + mi.getMethod().getName());
            obj = super.invoke(mi);
            PerformanceMonitor.end();
        } else {
            obj = super.invoke(mi);
        }
        return obj;
    }

    @Override
    public void setMonitorActive(boolean active) {
        MonitorStatus.set(active);
    }
}
